# -*- encoding:utf-8 -*-
__Author__ = "Wu Jin"

from flask import render_template, jsonify, request,flash
from flask import Blueprint
from app import db, oid
from flask.ext.login import login_required
from flask import g, redirect, session, url_for
from flask.ext.login import login_user, logout_user, current_user
from app.forms import LoginForm


sandbox = Blueprint('sandbox', __name__)

@sandbox.route('/')
@login_required
def show():
    return render_template('index.html')

@sandbox.route('/login',methods=['GET','POST'])
@oid.loginhandler
def login():
    form = LoginForm()
    if request.method=="POST":
        id = int(request.form["id"])
        password = request.form["password"]
        if id and password:
            from app.model import User
            user = User.query.filter(User.id==id).first()
            if user is not None and user.password==password:
                login_user(user)
                if user.role == 1:
                    return redirect("admin")
                return redirect("index")
            else:
                return render_template("login.html",msg="用户名或者密码错误")
    return render_template("login.html",form = form)


@sandbox.route('/logout',methods=['GET','POST'])
def logout():
    logout_user()
    return render_template('login.html')


@sandbox.route('/index')
@login_required
def index():
    return render_template('index.html')


@sandbox.route('/page1')
@login_required
def start():
    from app.model import User,serializer
    user = User.query.first()
    response = serializer.get_collection(db.session, {"fields[name]":"Tom"}, 'users')
    return render_template('funct/step1.html',user=response.data['data'])


@sandbox.route('/page2')
@login_required
def start2():
    from app.model import User,serializer
    user = User.query.first()
    response = serializer.get_collection(db.session, {}, 'users')
    return render_template('funct/step2.html',user=response.data['data'])


@sandbox.route('/page3')
@login_required
def start3():
    from app.model import User,serializer
    user = User.query.first()
    response = serializer.get_collection(db.session, {}, 'users')
    return render_template('funct/step3.html',user=response.data['data'])


@sandbox.route('/page4')
@login_required
def start4():
    from app.model import User,serializer
    user = User.query.first()
    response = serializer.get_collection(db.session, {}, 'users')
    return render_template('funct/step4.html',user=response.data['data'])
